<template>
  <div class="orderList-container">
    <byui-query-form>
      <el-form ref="form" :model="queryForm" label-width="80px">
        <el-row :gutter="20" type="flex">
          <div class="list-margin-lr" v-if="checkPermission(['root'])">
            <el-form-item label="团队管理" v-if="checkPermission(['root'])">
              <el-input v-model="adminName" autocomplete="off" placeholder="请输入团队管理用户名,按回车搜索" @keyup.enter.native="rootGetUnion"></el-input>
            </el-form-item>
          </div>
          <div class="list-margin-lr" v-if="checkPermission(['admin','root']) && unionList.length >0">
            <el-form-item label="联盟账号">
              <el-select v-model="unionForAdmin" placeholder="请选择">
                <el-option label="全部账号" value=""></el-option>
                <el-option :label="name" :value="name" v-for="(name, index) in unionList" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="list-margin-lr">
            <el-select v-model="queryForm.timeType" style="margin-right: -1px;width: 120px;">
              <el-option label="创建时间" value="1"></el-option>
              <el-option label="点击时间" value="2"></el-option>
              <el-option label="付款时间" value="3"></el-option>
              <el-option label="结算时间" value="4"></el-option>
            </el-select>
            <el-date-picker
              v-model="time"
              type="datetimerange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              style="margin-left: -1px;"
            ></el-date-picker>
          </div>
          <div class="list-margin-lr">
            <el-input placeholder="请输入内容" v-model="queryForm.q" class="input-with-select">
              <el-select v-model="queryForm.qSelect" slot="prepend" placeholder="请选择" style="width: 120px;">
                <el-option label="用户名" value="userName" v-if="checkPermission(['admin','root'])"></el-option>
                <el-option label="订单号" value="order"></el-option>
                <el-option label="商品ID" value="goodsId"></el-option>
                <el-option label="订单尾号" value="like"></el-option>
                <el-option label="商品名称" value="goodsName"></el-option>
              </el-select>
            </el-input>
          </div>
          <div class="list-margin-lr"><el-button type="primary" @click.native="handleQuery">查询</el-button></div>
        </el-row>
      </el-form>
    </byui-query-form>
    <div style="margin-bottom:10px;">
      <el-row :gutter="20" type="flex" justify="center">
        <el-col>
          <el-card class="box-card">
            <div class="text item total-money-title">全部销售额：</div>
            <div class="text item total-money-number">
              <byui-count :start-val="0" :end-val="totalData.alipay_total_price" :duration="3000" separator="," :decimals="0" />
              <span class="total-money-tip">元</span>
            </div>
            <div class="text item total-money-title">
              已退
              <byui-count :start-val="0" :end-val="totalData.falipay_total_price" :duration="3000" separator="," :decimals="0" />
              元
            </div>
          </el-card>
        </el-col>
        <el-col>
          <el-card class="box-card">
            <div class="text item total-money-title">全部佣金：</div>
            <div class="text item total-money-number">
              <byui-count :start-val="0" :end-val="totalData.pub_share_pre_fee" :duration="3000" separator="," :decimals="0" />
              <span class="total-money-tip">元</span>
            </div>
            <div class="text item total-money-title">
              <byui-count :start-val="0" :end-val="totalData.total" :duration="3000" separator="," :decimals="0" />
              单
            </div>
          </el-card>
        </el-col>
        <el-col>
          <el-card class="box-card">
            <div class="text item total-money-title">有效佣金：</div>
            <div class="text item total-money-number">
              <byui-count :start-val="0" :end-val="totalData.sComm" :duration="3000" separator="," :decimals="0" />
              <span class="total-money-tip">元</span>
            </div>
            <div class="text item total-money-title">
              <byui-count :start-val="0" :end-val="totalData.sTotal" :duration="3000" separator="," :decimals="0" />
              单
            </div>
          </el-card>
        </el-col>
        <el-col>
          <el-card class="box-card">
            <div class="text item total-money-title">退款佣金：</div>
            <div class="text item total-money-number">
              <byui-count :start-val="0" :end-val="totalData.fComm" :duration="3000" separator="," :decimals="0" />
              <span class="total-money-tip">元</span>
            </div>
            <div class="text item total-money-title">
              <byui-count :start-val="0" :end-val="totalData.fTotal" :duration="3000" separator="," :decimals="0" />
              单 退款率：{{ totalData.fRate }}%
            </div>
          </el-card>
        </el-col>
        <el-col>
          <el-card class="box-card">
            <div class="text item total-money-title">未付款订单：</div>
            <div class="text item total-money-number">
              <byui-count :start-val="0" :end-val="totalData.noPriceTotal" :duration="3000" separator="," :decimals="0" />
              <span class="total-money-tip">单</span>
            </div>
            <div class="text item total-money-title">未付款率：{{ totalData.noPriceRate }}%</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      header-row-class-name="tableHead"
      :cell-style="{ borderBottom: '0px' }"
      stripe
    >
      <el-table-column label="序号" width="80">
        <template slot-scope="scope">
          {{ scope.$index + 1 + (queryForm.pageNo - 1) * queryForm.pageSize }}
        </template>
      </el-table-column>
      <el-table-column label="订单信息" prop="title" width="420">
        <template slot-scope="scope">
          <el-row type="flex" class="row-bg" @click.native="goUrl(scope.row.item_id)" style="cursor:pointer">
              <div style="width: 90px; height: 90px; margin: auto;"><el-image :src="scope.row.item_img" style="width: 90px; height: 90px;"></el-image></div>
              <div style="margin-left: 10px;">
                <h4 style="max-width: 310px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;font-weight: 500;color: rgba(0, 0, 0, 0.85);">{{ scope.row.item_title }}</h4>
                <div style="font-size: 12px;text-align: left;">点击时间：{{ scope.row.click_time }}</div>
                <div style="font-size: 12px;text-align: left;">创建时间：{{ scope.row.tk_create_time }}</div>
                <div style="font-size: 12px;text-align: left;">付款时间：{{ scope.row.tb_paid_time }}</div>
              </div>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" prop="author">
        <template slot-scope="scope">
          <div v-if="scope.row.tk_status == 3" style="color: rgba(0, 0, 0, 0.85);">订单结算</div>
          <div v-if="scope.row.tk_status == 12" style="color: rgba(0, 0, 0, 0.85);">订单付款</div>
          <div v-if="scope.row.tk_status == 13" style="color: red;">订单失效</div>
          <div v-if="scope.row.tk_status == 14" style="color: rgba(0, 0, 0, 0.85);">订单成功</div>
        </template>
      </el-table-column>
      <el-table-column label="佣金比例" prop="total_commission_rate">
        <template slot-scope="scope">
          <div style="color: rgba(0, 0, 0, 0.85);">{{ scope.row.total_commission_rate }}%</div>
        </template>
      </el-table-column>
      <el-table-column label="预估收益" prop="pub_share_pre_fee">
        <template slot-scope="scope">
          {{ (scope.row.pub_share_pre_fee * 0.9).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="付款金额" prop="alipay_total_price"></el-table-column>
      <el-table-column label="联盟账号" prop="useUnion" v-if="checkPermission(['admin','root'])"></el-table-column>
      <el-table-column label="运营人" prop="username" v-if="checkPermission(['admin','root'])"></el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    ></el-pagination>
  </div>
</template>

<script>
import checkPermission from '@/utils/permission';
import { listUnionName,listOrder,totalOrder } from '@/api/index';
import ByuiCount from '@/plugins/byuiCount';
export default {
  name: 'OrderList',
  components: { ByuiCount },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours(0);
              start.setMinutes(0);
              start.setSeconds(0);
              start.setMilliseconds(0);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const today = new Date();
              today.setHours(0, 0, 0, 0);
              const start = new Date(today.getTime() - 86400000);
              const end = new Date(today.getTime() - 1);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '近3天',
            onClick(picker) {
              const today = new Date();
              today.setHours(0, 0, 0, 0);
              const start = new Date(today.getTime() - 86400000 * 3);
              const end = new Date(today.getTime() - 1);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '近7天',
            onClick(picker) {
              const today = new Date();
              today.setHours(0, 0, 0, 0);
              const start = new Date(today.getTime() - 86400000 * 7);
              const end = new Date(today.getTime() - 1);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '近30天',
            onClick(picker) {
              const today = new Date();
              today.setHours(0, 0, 0, 0);
              const start = new Date(today.getTime() - 86400000 * 30);
              const end = new Date(today.getTime() - 1);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '近90天',
            onClick(picker) {
              const today = new Date();
              today.setHours(0, 0, 0, 0);
              const start = new Date(today.getTime() - 86400000 * 90);
              const end = new Date(today.getTime() - 1);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      unionList: [],
      list: [],
      listLoading: false,
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      background: true,
      elementLoadingText: '正在加载...',
      queryForm: {
        pageNo: 1,
        pageSize: 20,
        timeType: '1',
        qSelect: 'goodsName',
        q: '',
        startTime: dateFormat('YYYY-mm-dd HH:MM:SS', today()),
        endTime: dateFormat('YYYY-mm-dd HH:MM:SS', new Date())
      },
      unionForAdmin: '',
      time: [today(),new Date()],
      totalData: {},
      adminName:''
    };
  },
  created() {
    if (this.checkPermission(['admin'])) {
      listUnionName({}).then(res => {
        if (res.code && res.code === 200) {
          this.unionList = res.data;
          if (res.data.length == 0) {
            this.$baseAlert('必须先添加淘宝账号', '请先添加账号', () => {
              this.$router.push('/admin/unionTaobao');
            });
          }
        }
      });
    }
    this.fetchData();
  },
  beforeDestroy() {},
  mounted() {},
  methods: {
    rootGetUnion(e){
      if(this.adminName.length < 1){
        return this.$baseMessage('请输入正确的管理员名字，然后按回车', 'error');
      }
      listUnionName({'username':this.adminName}).then(res => {
        if (res.code && res.code === 200) {
          this.unionList = res.data;
          if (res.data.length == 0) {
            this.$baseAlert('该账号没有添加联盟账号', '请先添加账号', () => {

            });
          }
        }
      });
    },
    goUrl(id){
      window.open('https://detail.tmall.com/item.htm?id='+id)
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val;
      this.fetchData();
    },
    handleQuery() {
      let req = this.queryForm;
      if (this.checkPermission(['admin','root'])) {
        req.name = this.unionForAdmin;
      }
      if (this.time && this.time.length == 2) {
        req.startTime = dateFormat('YYYY-mm-dd HH:MM:SS', this.time[0]);
        req.endTime = dateFormat('YYYY-mm-dd HH:MM:SS', this.time[1]);
      }else{
        req.startTime = ''
        req.endTime = ''
      }
      this.queryForm.pageNo = 1;
      this.fetchData();
    },
    fetchData() {
      if (this.queryForm.pageNo === 1) {
        totalOrder(this.queryForm).then(res => {
          if (res.code === 200) {
            this.totalData = res.data;
          }
        });
      }
      listOrder(this.queryForm).then(res => {
        this.list = res.data;
        const imageList = [];
        res.data.forEach((item, index) => {
          imageList.push(item.img);
        });
        this.imageList = imageList;
        this.total = res.totalCount;
        setTimeout(() => {
          this.listLoading = false;
        }, 500);
      });
    },
    checkPermission
  }
};
function dateFormat(fmt, date) {
  let ret;
  const opt = {
    'Y+': date.getFullYear().toString(), // 年
    'm+': (date.getMonth() + 1).toString(), // 月
    'd+': date.getDate().toString(), // 日
    'H+': date.getHours().toString(), // 时
    'M+': date.getMinutes().toString(), // 分
    'S+': date.getSeconds().toString() // 秒
  };
  for (let k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'));
    }
  }
  return fmt;
}
function today(){
  let today = new Date();
  today.setHours(0, 0, 0, 0);
  return today
}
</script>

<style lang="scss">
.tableHead {
  height: 70px;
}
.goods_wrapper {
  position: relative;
  width: 90px;
  height: 90px;
  margin-top: 5px;
  padding-right: 5px;
}
.list-margin-lr {
  margin: 0 10px;
}
.list-title {
  color: #444;
}
.el-table::before {
  height: 0;
}
.total-money-title {
  font-size: 12px;
  color: #999;
  line-height: 20px;
}
.total-money-number {
  font-size: 24px;
  font-weight: 700;
  margin: 0;
  color: #2361ff;
  line-height: 36px;
}
.total-money-tip {
  font-size: 12px;
  font-weight: bold;
  color: rgb(35, 97, 255);
  margin-left: 5px;
}
</style>
